<template>
    <div>
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">考试</a></el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">考试详情</a></el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">试卷详情</a></el-breadcrumb-item>
        <el-breadcrumb-item>选择试题</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="subjectTitle">
<!--   占位符    -->
        <div></div>
        <div></div>
        <div>
          <el-button type="primary" @click="addToPaper">增加已选至试卷</el-button>
          <el-button @click="back">返回</el-button>
        </div>
      </div>
      <div style="width: 90%; margin-left: 5%; margin-top: 10px;">
        <el-table
          ref="multipleTable"
          :data="questionList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            prop="stem"
            label="题目"
            width="200">
          </el-table-column>
          <el-table-column
            prop="subject"
            label="科目"
            width="140">
          </el-table-column>
          <el-table-column
            prop="knowledgePoint"
            label="知识点"
            width="140">
          </el-table-column>
          <el-table-column
            prop="teacherNumber"
            label="老师"
            width="140">
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="createTime">
          </el-table-column>
          <el-table-column
            label="更新时间"
            prop="updateTime">
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            layout="total, prev, pager, next"
            :page-size="pagination.page_size"
            :current-page="pagination.index"
            :total="pagination.total"
            @current-change="changePage">
          </el-pagination>
        </div>
<!--        <div style="margin-top: 20px">-->
<!--          <el-button @click="toggleSelection(questionList[0])">1</el-button>-->
<!--          <el-button @click="toggleSelection(questionList[1])">1</el-button>-->
<!--          <el-button @click="toggleSelection(questionList[2])">1</el-button>-->
<!--          <el-button @click="toggleSelection(questionList[3])">1</el-button>-->
<!--          <el-button @click="toggleSelection()">取消选择</el-button>-->
<!--        </div>-->
      </div>
    </div>
</template>

<script>
import {questionSearchAdd} from '../../../api/questions'

export default {
  name: 'QuestionForPaper',
  data () {
    return {
      // 分页信息
      pagination: {
        page_size: 5,
        index: 1,
        total: 100
      },
      // 科目和题型
      subjectId: 0,
      questionType: '',
      // 筛选条件
      condition: '',
      conditions: ['创建时间', '更新时间', '科目', '知识点', '老师', '题干'],
      // 表格显示
      questionList: [
        {
          answer: 'A',
          createTime: '2022-03-24 14:18:34',
          id: 1,
          knowledgePointId: 2,
          questionStem: '{"stem":"192.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。","options":{"A":"14 14","B":"16 14","C":"254 6","D":"14 62"}}',
          questionType: 'radio',
          subjectId: 1,
          teacherId: 1,
          updateTime: '2022-03-24 14:18:34',
          stem: '92.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。'
        },
        {
          answer: 'A',
          createTime: '2022-03-24 14:18:34',
          id: 1,
          knowledgePointId: 2,
          questionStem: '{"stem":"192.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。","options":{"A":"14 14","B":"16 14","C":"254 6","D":"14 62"}}',
          questionType: 'radio',
          subjectId: 1,
          teacherId: 1,
          updateTime: '2022-03-24 14:18:34',
          stem: '92.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。'
        },
        {
          answer: 'A',
          createTime: '2022-03-24 14:18:34',
          id: 1,
          knowledgePointId: 2,
          questionStem: '{"stem":"192.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。","options":{"A":"14 14","B":"16 14","C":"254 6","D":"14 62"}}',
          questionType: 'radio',
          subjectId: 1,
          teacherId: 1,
          updateTime: '2022-03-24 14:18:34',
          stem: '92.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。'
        }
      ],
      // 多选结果
      multipleSelection: []
    }
  },
  mounted () {
    this.subjectId = this.$route.query.subjectId
    this.questionType = this.$route.query.questionType
    this.getQuestions()
  },
  methods: {
    // 将该题型选择保存至前端
    addToPaper () {
      const questionIdArray = []
      this.multipleSelection.forEach(question => {
        questionIdArray.push(question.id)
      })
      console.log(questionIdArray)
      let order = JSON.parse(sessionStorage.getItem('questionOrder'))
      if (this.questionType === 'radio') {
        order[0] = questionIdArray
      } else if (this.questionType === 'multiple') {
        order[1] = questionIdArray
      } else if (this.questionType === 'filling') {
        order[2] = questionIdArray
      } else {
        order[3] = questionIdArray
      }
      sessionStorage.setItem('questionOrder', JSON.stringify(order))
      this.$router.go(-1)
    },
    // 不保存直接返回
    back () {
      this.$router.go(-1)
    },
    // 翻页
    changePage (val) {
      this.pagination.index = val
      this.getQuestions()
    },
    // 根据科目和题型获取题目
    getQuestions () {
      let parameter = {
        page_size: this.pagination.page_size,
        index: this.pagination.index - 1,
        subjectId: this.subjectId,
        questionType: this.questionType,
        examQuestion: true
      }
      questionSearchAdd(parameter).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          console.log(res.data)
          this.questionList = res.data.data.list
          this.pagination.total = res.data.data.total
          // 转化格式
          for (let i = 0; i < this.questionList.length; i++) {
            this.questionList[i].stemShow = this.transferForm(this.questionList[i])
            this.questionList[i].stem = JSON.parse(this.questionList[i].questionStem).stem
            this.questionList[i].options = JSON.parse(this.questionList[i].questionStem).options
          }
          this.autoSelect()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 转化格式
    transferForm (questionDetail) {
      let stem = JSON.parse(questionDetail.questionStem)
      let temp = stem.stem
      var count = 0
      for (var i = 0; i < temp.length; i++) {
        // eslint-disable-next-line no-control-regex
        if (temp.charAt(i).replace(/[^\x00-\xff]/g, 'rr').length > 1) {
          count += 2
        } else {
          count += 1
        }
        if (count >= 30) {
          return temp.slice(0, i) + '...'
        }
      }
      return temp
    },
    transferType (type) {
      switch (type) {
        case 'radio': return '单选'
        case 'multiple': return '多选'
        case 'filling': return '填空'
        case 'shortAnswer': return '简答'
        default: return 'error'
      }
    },
    handleSelectionChange (val) {
      console.log(val)
      this.multipleSelection = val
    },
    autoSelect () {
      let order = JSON.parse(sessionStorage.getItem('questionOrder'))
      let group
      if (this.questionType === 'radio') {
        group = order[0]
      } else if (this.questionType === 'multiple') {
        group = order[1]
      } else if (this.questionType === 'filling') {
        group = order[2]
      } else {
        group = order[3]
      }

      this.$nextTick(() => {
        for (let i = 0; i < this.questionList.length; i++) {
          if (group.indexOf(this.questionList[i].id) > -1) {
            console.log(i)
            this.$refs.multipleTable.toggleRowSelection(this.questionList[i])
          }
        }
      })
    }
  }
}
</script>

<style scoped>
  .breadcrumb {
    padding: 20px;
  }

  .subjectTitle {
    font-size: 25px;
    font-weight: bold;
    margin: 0 20px;
    display: grid;
    grid-template-columns: 25% 50% 25%;
  }
</style>
